package resolver

import (
	"fmt"
	"gitee.com/vrv_media/go-micro-framework/registry"
	"strconv"
)

// ResolverNode 服务解析后的默认节点
type ResolverNode struct {
	id          string
	serviceName string
	addr        string
	weight      *int64
	version     string
	scheme      string
	metadata    map[string]string
	tags        []string
	instance    interface{}
}

func NewNodeWithServiceInstance(ins *registry.ServiceInstance) registry.Node {
	return newNode(&ResolverNode{}, ins)
}

// New new node
func New(scheme, addr string, ins *registry.ServiceInstance) registry.Node {
	n := &ResolverNode{
		scheme: scheme,
		addr:   addr,
	}
	return newNode(n, ins)
}

func newNode(n *ResolverNode, ins *registry.ServiceInstance) *ResolverNode {
	if ins != nil {
		n.id = ins.ID
		n.serviceName = ins.Name                   // 服务发现设置的名字
		n.version = ins.Version                    // 服务发现设置的版本号
		n.metadata = ins.Metadata                  // 元数据
		if str, ok := ins.Metadata["weight"]; ok { // 是否 元数据中携带 初始权重
			if weight, err := strconv.ParseInt(str, 10, 64); err == nil {
				n.weight = &weight
			}
		}
		if len(ins.Endpoints) > 0 {
			n.addr = ins.Endpoints[0]
		}
	}
	return n
}
func (r *ResolverNode) Key() string {
	return fmt.Sprintf("%s_%s_%s", r.serviceName, r.addr, r.id)
}

func (r *ResolverNode) Scheme() string {
	return r.scheme
}

func (r *ResolverNode) Address() string {
	return r.addr
}

func (r *ResolverNode) ServiceName() string {
	return r.serviceName
}

func (r *ResolverNode) Weight() int64 {
	if r.weight == nil {
		return 0
	}
	return *r.weight
}
func (r *ResolverNode) UpdateWeight(weight int64) {
	r.weight = &weight
}
func (r *ResolverNode) Version() string {
	return r.version
}

func (r *ResolverNode) Metadata() map[string]string {
	return r.metadata
}

func (r *ResolverNode) Instance() interface{} {
	return r.instance
}

func (r *ResolverNode) Tags() []string {
	return r.tags
}

func (r *ResolverNode) SetInstance(instance interface{}) {
	r.instance = instance
}
